package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 刘付磊
 * @date 2021/10/14 0014
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements EmployeeService {

    @Autowired
    public EmployeeMapper employeeMapper;

    @Override
    public R<Employee> login(Employee employee) {
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeMapper.selectOne(lqw);
        if(emp == null){
            return R.error("账号不存在");
        }
        String psd = employee.getPassword();
        psd= DigestUtils.md5DigestAsHex(psd.getBytes());
        if(!psd.equals(emp.getPassword())){
            return R.error("密码错误");
        }
        if(emp.getStatus()!=1){
            return R.error("账号被禁用");
        }
        return R.success(emp);
    }

    @Override
    public R<String> logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return R.success("取消登录成功");
    }

   /* @Override
    public R<String> save(HttpServletRequest request, Employee employee) {
        //1.设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //2.设置修改时间和创造时间
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateTime(LocalDateTime.now());
        //3.设置修改对象的ID 和 创建对象的ID
        Long id = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(id);
        employee.setUpdateUser(id);
        employeeMapper.insert(employee);
        return R.success("添加成功");
    }*/

    @Override
    public R<Page<Employee>> findPageEndName(String name,int page, int pageSize) {
        //1.构造分页构造器
        Page pg = new Page(page,pageSize);
        //2.构造条件构造器
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper();
        //3.添加过滤条件
        lqw.like(StringUtils.isNotBlank(name),Employee::getUsername,name);
        //4.添加排序条件
        lqw.orderByDesc(Employee::getUpdateTime);
        //5.执行sql语句
        Page<Employee> emp = employeeMapper.selectPage(pg, lqw);
        return R.success(emp);
    }
}
